/**
 * @author: qwesde@hust.edu.cn
 * @date: 2021/2/10 23:38
 */
import router from './router'
import NProgress from 'nprogress'
import {getToken} from "./utils/auth";
import UserType from "./common/userType";
import {Message} from "element-ui";
import store from "./store";

const LoginUrl = '/user/login'
const RegisterUrl= '/user/signup'

const whiteList = [LoginUrl,RegisterUrl]

router.beforeEach((to, from, next) => {
    NProgress.start();
    if (getToken()) {
        if (to.path === LoginUrl) {
            NProgress.done();
            next({path: '/'}) // 已经登陆的，再次登陆直接定位到主页
        } else {
            if (store.getters.userType === UserType.unknown) {
               // 用户信息不存在需要重新加载
               store.dispatch("GetUserInfo").then(res => {
                   let menus = res.data.menus || [];
                   store.dispatch("GenerateRouters", { menus }).then(() => {
                       router.addRoutes(store.getters.addRouters);
                       next({ ...to, replace: true });
                   })
               }).catch(err => {
                   // 获取认证用户信息失败，需要重新登陆
                   store.dispatch("Logout").then(res => {
                       Message.error(err || "Verification failed, please login again.")
                       next({path: "/"})
                   })
               })
            } else {
                if (to.matched.length === 0) { // 一个不存在的页面, 取消导航
                    next(false);
                } else {
                    next(); // okay
                }
            }
        }
    } else {
        // 未登录

        // 在白名单中
        if (whiteList.indexOf(to.path) !== -1)
            next();
        else {
            next(LoginUrl);
            NProgress.done();
        }
    }
})

router.afterEach(() => {
    NProgress.done();
})
